import Course from "../../components/course";
import { CapsuleTabs, Tabs } from "antd-mobile";
import { categoryGet } from "../../api/course";
import { CategoryType } from "../../types/course";
import { useEffect, useState } from "react";
import "./index.scss";
export default function Explore() {
  let [cateList, setCateList] = useState<Array<CategoryType>>([]);
  let [activeLv1, setActiveLv1] = useState<number>(0);
  let [activeLv2, setActiveLv2] = useState<string>("all");
  useEffect(() => {
    categoryGet().then((res) => {
      let { results } = res.data;
      let parentArr = results.filter(
        (item: CategoryType) => item.parentId == "0-0"
      );
      parentArr.forEach((item: CategoryType) => {
        let children = results.filter(
          (child: CategoryType) => item.objectId == child.parentId
        );
        item.children = children;
      });
      console.log("处理后数据", parentArr);

      setCateList(parentArr);
    });
  }, []);
  const handleCapsule = (key: string) => {
    console.log("一级id", cateList[Number(key)].name); //一级类目名称
    setActiveLv1(Number(key));
    setActiveLv2("all"); //重置二级类目
  };
  const handleTabs = (key: string) => {
    setActiveLv2(key);
    console.log("二级名称", key);
  };
  return (
    <>
      <CapsuleTabs defaultActiveKey={activeLv1 + ""} onChange={handleCapsule}>
        {cateList.map((item: CategoryType, index: number) => {
          return <CapsuleTabs.Tab title={item.name} key={index} />;
        })}
      </CapsuleTabs>
      <Tabs onChange={handleTabs} activeKey={activeLv2}>
        <Tabs.Tab title="全部" key="all" />;
        {cateList[activeLv1]?.children!.map((item) => {
          return <Tabs.Tab title={item.name} key={item.name} />;
        })}
      </Tabs>
      {/* lv1为一级类目的名称，lv2是二级类目的名称，通过props父子通信传给Course组件 */}
      <Course lv1={cateList[activeLv1]?.name} lv2={activeLv2} />
    </>
  );
}
